package com.yakaten.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.seasar.framework.util.ResourceUtil;

import com.yakaten.dto.KakakuItemInfoDto;
import com.yakaten.dto.KakakuPriceTaskDto;
import com.yakaten.dto.TaskInfoDto;
import com.yakaten.exception.KakakuException;
import com.yakaten.exception.MakeShopException;
import com.yakaten.exception.SystemException;
import com.yakaten.logic.KakakuPriceLogic;
import com.yakaten.logic.TaskInfoLogic;
import com.yakaten.login.KakakuLogin;
import com.yakaten.login.MakeShopLogin;

public class KakakuPriceRunner extends Thread {
	static Logger logger = Logger.getLogger(KakakuPriceRunner.class);

	private static final SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	String SHOP_NAME = ResourceUtil.getProperties("yakaten.properties")
	.getProperty("system.shopName");

	public static int KENKAKU = 10;

	private KakakuItemService kakakuItemService = new KakakuItemService();

	private List<KakakuPriceTaskDto> needStopList = new ArrayList<KakakuPriceTaskDto>();

	public void start() {
		super.start();
	}

	public List<KakakuPriceTaskDto> getWorkList() {
		List<KakakuPriceTaskDto> workList = new ArrayList<KakakuPriceTaskDto>();
		KakakuPriceLogic logic = new KakakuPriceLogic();
		try {
			List<KakakuPriceTaskDto> taskList = logic.getAllTaskList();
			Iterator<KakakuPriceTaskDto> taskListIt = taskList.iterator();
			while (taskListIt.hasNext()) {
				KakakuPriceTaskDto currentTask = taskListIt.next();
				if (currentTask.getStatus() == 1) {
					List<KakakuItemInfoDto> kakakuInfoList = kakakuItemService.getItemInfo(currentTask.getKakakuItemId());

					if(needStopTask(kakakuInfoList)){
//						currentTask.setStatus(0);
//						needStopList.add(currentTask);
					}else{
						KakakuItemInfoDto kakakuItemInfo = kakakuInfoList.get(0);
						currentTask.setKakakuItemName(kakakuItemInfo.getItemName());

						if(SHOP_NAME.equals(kakakuItemInfo.getShopName())){
							if(kakakuInfoList.size()>1){
								KakakuItemInfoDto kakakuItemInfoSecond = kakakuInfoList.get(1);
								if("1".equals(currentTask.getKakakuItemSyoryuCalculate())){
									currentTask.setWorkPrice(kakakuItemInfoSecond.getItemPrice()+kakakuItemInfoSecond.getSyoryu()-1);
								}else{
									currentTask.setWorkPrice(kakakuItemInfoSecond.getItemPrice()-1);
								}

//								if(currentTask.getShopItemPrice()<currentTask.getWorkPrice()){
									workList.add(currentTask);
//								}
							}

						}else{
							//
							if(currentTask.getCompareShopName()!=null && currentTask.getCompareShopName().length()>0){
								for(KakakuItemInfoDto current:kakakuInfoList){
									if(currentTask.getCompareShopName().equals(current.getShopName())){
										kakakuItemInfo = current;
										break;
									}
								}
							}
							long kakakuItemPrice = kakakuItemInfo.getItemPrice();
							currentTask.setKakakuItemPrice(kakakuItemPrice);

							if(logger.isInfoEnabled()){
								logger.info(currentTask.toString());
							}
							if("1".equals(currentTask.getKakakuItemSyoryuCalculate())){
								currentTask.setWorkPrice(kakakuItemPrice+kakakuItemInfo.getSyoryu()-currentTask.getComparePrice());
							}else{
								currentTask.setWorkPrice(kakakuItemPrice-currentTask.getComparePrice());
							}

							if(currentTask.getWorkPrice() >= currentTask.getMinPrice()) {
								workList.add(currentTask);
							}
						}
					}

				}
			}
		} catch (SystemException e) {
			logger.error(e);
		} catch (KakakuException e) {
			logger.error(e);
		}
		return workList;
	}

	public List<KakakuPriceTaskDto> updateKakaku(List<KakakuPriceTaskDto> workList) throws SystemException{
		List<KakakuPriceTaskDto> resultList =new ArrayList<KakakuPriceTaskDto>();

		InputStreamReader ir = null;
		File outputFile = null;
		File csvFile = null;
		try {
			KakakuLogin login = new KakakuLogin();
//			String userName = ResourceUtil.getProperties("yakaten.properties")
//			.getProperty("kakaku.login.userName");
//
//			String passwd = ResourceUtil.getProperties("yakaten.properties")
//			.getProperty("kakaku.login.passwd");

			TaskInfoDto dto = new TaskInfoDto();
			dto.setInfoNo("1");
			TaskInfoLogic taskInfoLogic = new TaskInfoLogic();
			dto=taskInfoLogic.getTaskInfo(dto);

			String userName = ResourceUtil.getProperties("yakaten.properties")
			.getProperty("kakaku.login.userName");
			String passwd = ResourceUtil.getProperties("yakaten.properties")
			.getProperty("kakaku.login.passwd");
			if(dto!=null){
				userName=dto.getUserName();
				passwd=dto.getPassword();
			}




			boolean loginResult = login.doLogin(userName, passwd);
			if(logger.isInfoEnabled()){
				logger.info("kakaku login:"+loginResult);
			}

			csvFile = kakakuItemService.getCsvFile();
			if(logger.isInfoEnabled()){
				logger.info("kakaku file:"+(csvFile==null?" error ":csvFile.getPath()));
			}

			if(csvFile!=null && csvFile.exists()){
				ir = new InputStreamReader(new FileInputStream(
						csvFile), "shift_jis");
				BufferedReader br = new BufferedReader(ir);
				String current = "";
				StringBuffer output = new StringBuffer();
				while ((current = br.readLine()) != null) {
					String workLine = current;
					String data[] =current.split(",");
					String csvItemName = data[1];
					Iterator<KakakuPriceTaskDto> it =workList.iterator();
					while(it.hasNext()){
						KakakuPriceTaskDto currentDto = it.next();
						if(csvItemName.trim().equals(currentDto.getKakakuItemName().trim())){

							int itemCount =0;
							try{
								itemCount = Integer.parseInt(currentDto.getQuantity());
							}catch(NumberFormatException e){
								logger.error(e);
							}

							if(itemCount>0){
								data[2]=""+currentDto.getWorkPrice();
								StringBuffer tmp = new StringBuffer();
								for(int i=0;i<data.length;i++){
									tmp.append(data[i]+",");
								}
								workLine =tmp.substring(0, tmp.length()-1);
							}else{
								currentDto.setStatus(3);
								workLine = null;
							}

							resultList.add(currentDto);
						}
					}
					if(workLine!=null){
						output.append(workLine+"\r\n");
					}
				}
				String outputFileName =csvFile.getPath().replace(".bak", "");
				outputFile = new File(outputFileName);
				IOUtils.write(output, new FileOutputStream(outputFile),
				"shift_jis");

				boolean uploadResult = kakakuItemService.uploadCsvFile(outputFile);
				if(logger.isInfoEnabled()){
					logger.info("kakaku upload file:"+uploadResult);
				}

				KakakuPriceRunner.sleep(10 * 1000);

				boolean uploadConfirmResult = kakakuItemService.uploadCsvConfirm();
				if(logger.isInfoEnabled()){
					logger.info("kakaku upload file confirm:"+uploadConfirmResult);
				}
			}

		} catch (KakakuException e) {
			logger.error(e);
		} catch (UnsupportedEncodingException e) {
			logger.error(e);
		} catch (FileNotFoundException e) {
			logger.error(e);
		} catch (IOException e) {
			logger.error(e);
		} catch (InterruptedException e) {
			logger.error(e);
		}finally{
			if(ir!=null){
				try {
					ir.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(outputFile!=null){
				outputFile.delete();
			}

			if(csvFile!=null){
				csvFile.delete();
			}

		}


		return resultList;
	}

	public List<KakakuPriceTaskDto> updateMyShop(List<KakakuPriceTaskDto> workList){
		List<KakakuPriceTaskDto> resultList =new ArrayList<KakakuPriceTaskDto>();

//		try {
			MakeShopLogin login = new MakeShopLogin();
			String userName = ResourceUtil.getProperties("yakaten.properties")
			.getProperty("makeshop.login.userName");

			String passwd = ResourceUtil.getProperties("yakaten.properties")
			.getProperty("makeshop.login.passwd");
			boolean loginResult;
			try {
				loginResult = login.doLogin(userName, passwd);
				if(logger.isInfoEnabled()){
					logger.info("my shop login:"+loginResult);
				}
			} catch (MakeShopException e1) {
				logger.error("my shop login failed!");
				logger.error(e1);
			}


			MakeShopItemService service = new MakeShopItemService();
			Iterator<KakakuPriceTaskDto> it =workList.iterator();
			while(it.hasNext()){
				KakakuPriceTaskDto current = it.next();
				Map<String, String> valueMap = null;
				try {
					valueMap = service.getItemInfo(current.getShopItemId());
					try {

						KakakuPriceRunner.sleep(1  * 1000);
					} catch (InterruptedException e) {
						logger.error(e);
					}
				} catch (MakeShopException e1) {
					logger.error("my shop getItemInfo failed!");
					logger.error(e1);
					continue;
				}
				String quantity =service.getQuantity(valueMap);
				int itemCount=0;
				try{
					if("".equals(quantity)){
						itemCount=1;
						logger.error("get shop quantity  error."+current.toString());
					}else{
						itemCount = Integer.parseInt(quantity);
					}

				}catch(NumberFormatException e){
					logger.error(e);
				}

				if(itemCount>0){
//					if(current.getWorkPrice() != current.getShopItemPrice()){
						valueMap.put(new String("type"), "upd");
						valueMap.put(new String("sellprice"), ""+current.getWorkPrice());
						boolean updateShopResult = false;
						try {
							updateShopResult = service.updateItemInfo(valueMap);
							try {

								KakakuPriceRunner.sleep(1  * 1000);
							} catch (InterruptedException e) {
								logger.error(e);
							}
						} catch (MakeShopException e) {
							logger.error("my shop updateShopResult failed!");
							logger.error(e);
							continue;
						}
						if(updateShopResult){
							if(logger.isInfoEnabled()){
								logger.info("update shop price "+updateShopResult+" >>> shopItemId:"+current.getShopItemId()+":"+current.getShopItemName()+" >  "+current.getShopItemPrice()+" >>> "+current.getWorkPrice());
							}
							current.setShopItemPrice(current.getWorkPrice());
							resultList.add(current);
						}
//					}

				}else{
					if(logger.isInfoEnabled()){
						logger.info("quantity 0 >>> shopItemId:"+current.getShopItemId()+":"+current.getShopItemName());
					}
					current.setQuantity("0");
					resultList.add(current);
				}

			}
//		} catch (MakeShopException e) {
//			logger.error(e);
//		}
		return resultList;
	}

	public static void main(String [] args){
//		String str [] = {"a","b","b","d"};
//		String tmp = Arrays.toString(str);
//		System.out.println(tmp.substring(1, tmp.length()-1));
//		KakakuPriceRunner runner = new KakakuPriceRunner();
//		List<KakakuPriceTaskDto> workList = new ArrayList<KakakuPriceTaskDto>();
//		KakakuPriceTaskDto dto1 = new KakakuPriceTaskDto();
//		dto1.setKakakuItemName("RC-18VQC(N)");
//		dto1.setKakakuItemPrice(16290);
//		dto1.setQuantity("0");
//		workList.add(dto1);

//		KakakuPriceTaskDto dto2 = new KakakuPriceTaskDto();
//		dto2.setKakakuItemName("FU-Z30CX-W [ホワイト系]");
//		dto2.setKakakuItemPrice(888888888);
//		workList.add(dto2);


//		List<KakakuPriceTaskDto> workList = new ArrayList<KakakuPriceTaskDto>();
//		KakakuPriceTaskDto dto1 = new KakakuPriceTaskDto();
//		dto1.setShopItemId("005010000005");
//		dto1.setKakakuItemPrice(88888);
//		workList.add(dto1);

//		KakakuPriceTaskDto dto2= new KakakuPriceTaskDto();
//		dto2.setShopItemId("005010000010");
//		dto2.setKakakuItemPrice(66666);
//		workList.add(dto2);
//
//		KakakuPriceTaskDto dto3= new KakakuPriceTaskDto();
//		dto3.setShopItemId("005010000011");
//		dto3.setKakakuItemPrice(77777);
//		workList.add(dto3);
//
//		runner.updateMyShop(workList);
//		File file = new File("C:/yakaten/logs/1.bak");
//		file.deleteOnExit();
//		System.out.println(file.delete());
		logger.error("111");
	}

	public void run() {
		while (true) {
			try{
				TaskInfoDto dto = new TaskInfoDto();
				dto.setInfoNo("1");
				TaskInfoLogic taskInfoLogic = new TaskInfoLogic();
				String status="0";
				dto=taskInfoLogic.getTaskInfo(dto);
				if(dto!=null){
					status=dto.getRunStatus();
				}
				if("1".equals(status)){

					if(logger.isInfoEnabled()){
						String message = "--------kakaku task start on:"+sf.format(new Date())+"---------";
						logger.info(message);
					}

					List<KakakuPriceTaskDto> workList = getWorkList();
					if(workList.size()>0){
						List<KakakuPriceTaskDto> updateMyShopResult= updateMyShop(workList);
						if(updateMyShopResult.size()>0){
							List<KakakuPriceTaskDto> updateKakakuResult = updateKakaku(updateMyShopResult);
							if(updateKakakuResult.size()>0){
								KakakuPriceLogic logic = new KakakuPriceLogic();
								logic.updateTask(updateKakakuResult);
							}
						}

					}

					if(needStopList.size()>0){
						KakakuPriceLogic logic = new KakakuPriceLogic();
						logic.updateTask(needStopList);

						needStopList.clear();
					}

				}

			}catch(Exception e){
				logger.error(e);
			}finally{
				if(logger.isInfoEnabled()){
					String message = "--------kakaku task end on:"+sf.format(new Date())+"---------";
					logger.info(message);
				}
			}

			// this.sleep(10*60*1000);
			try {
				KakakuPriceRunner.sleep(KENKAKU  * 1000);
			} catch (InterruptedException e) {
				logger.error(e);
			}
		}
	}

	private boolean needStopTask(List<KakakuItemInfoDto> kakakuInfoList){
		boolean needStopTask = true;

		if(kakakuInfoList==null || kakakuInfoList.size()==0){
			return true;
		}else{
			for(KakakuItemInfoDto current:kakakuInfoList){
				if(SHOP_NAME.equals(current.getShopName())){
					needStopTask = false;
					break;
				}
			}
		}

		return needStopTask;
	}
}
